<template>
  <div class="first-page">
    <div class="top-count">
      <div class="item top-count-left">
        <div class="item-top">
          <div class="item-top-l">
            <img src="@/assets/top_left_icon.png" alt="">
          </div>
          <div class="item-top-r">
            <span class="count">活跃应用累计总量</span>
            <div class="text">
              <p v-if="!total_active_num">----</p>
              <ComNumberScroll v-else :start="total_active_num_start" :end="total_active_num" :autoPlay="true"
                :duration="1000" :default="0" showType="no-bg" />
            </div>
          </div>
        </div>
      </div>
      <div class="item top-count-center">
        <div class="inner">
          <p class="text">今日应用启动总量</p>
          <div class="num-box">
            <template v-if="!today_app_startup_num">
              <div v-for="(item, index) in '----'" :key='index' class="num-box-item">
                <span>{{ item }}</span>
              </div>
            </template>
            <ComNumberScroll v-else :start="today_app_startup_num_start" :end="today_app_startup_num" :autoPlay="true"
              :duration="1000" :default="0" />
          </div>
        </div>
      </div>
      <div class="item top-count-right">
        <div class="item-top">
          <div class="item-top-l">
            <img src="@/assets/top_right_icon.png" alt="">
          </div>
          <div class="item-top-r">
            <span class="count">昨日应用启动总量</span>
            <div class="text">
              <ComNumberScroll :start="0" :end="yesterdayCount" :autoPlay="true" :duration="1000" :default="0"
                showType="no-bg" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="center-box">
      <div class="center-box-left">
        <ComNavTab text="应用启动总量分布" />
        <ComBaseEcharts echartId="applySumId" :options="getOptionsForAppAllPieRef"
          :customStyle="{ width: '100%', height: '100%' }" />
      </div>
      <div class="center-box-center">
        <ComNavTab text="应用启动地域分布" />
        <ComMap echartId="firstAllPage" style="width:85%;height:85%;" :data="centerMapData" />
      </div>
      <div class="center-box-right">
        <div class="center-box-right-top">
          <ComNavTab text="近7天应用启动" />
          <div class="layout-right">
            <div class="layout-right-num">{{ sevenTotal }}</div>
            <ComBaseEcharts echartId="sevenAppStart" :options="getOptionsForRightpieSevenRef"
              :customStyle="{ width: '180px', height: '180px' }" />
          </div>

        </div>
        <div class="center-box-right-bottom">
          <ComNavTab text="近15天应用启动" />
          <div class="layout-right">
            <div class="layout-right-num">{{ fifteenTotal }}</div>
            <ComBaseEcharts echartId="fifteenAppStart" :options="getOptionsForRightpieRef"
              :customStyle="{ width: '180px', height: '180px' }" />
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-box">
      <div class="bottom-box-left">
        <ComNavTab text="应用启动趋势" />
        <div class="tab-wrapper">
          <div class="tab-container">
            <div class="tabs">
              <div class="tabs-item" v-for="tab in tabs" :key="tab.value"
                :class="['tab-button', { active: currentTab === tab.value }]" @click="currentTabClick(tab.value)">
                {{ tab.label }}
              </div>
            </div>
          </div>
        </div>
        <ComBaseEcharts echartId="LineBottomRe" :options="getOptionsForLineBottomRef" style="width:100%;height:80%;" />
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getYesterday, getLast7Days, getLast15Days, getLast30Days } from '@/utils/func/util'
import ComNavTab from '@/components/public/ComNavTab.vue';
import ComMap from '@/components/public/ComMap.vue';
import ComBaseEcharts from '@/components/public/ComBaseEcharts.vue'
import { getOptionsForLineBottom, getOptionsForRightpie, getOptionsForAppAllPie } from './option.js'
import ComNumberScroll from '@/components/public/ComNumberScroll/ComNumberScroll.vue';
import {
  getTotalActiveNum,
  getTodayAppStartUpNum,
  getStartTotal,
  getAppSum,
  getRegionSum,
  getTodayRegionSum,
  getYesterdayStart
} from '@/api/sdk/sdk.js'
import china from '@/json/china.json'



const intervalId = ref(null);
const intervalAllId = ref(null);
const interval5minCount = ref(null);

const total_active_num_start = ref(0)
const prevData = ref(0)
const today_app_startup_num_start = ref(0)
const total_active_num = ref(0)
const today_app_startup_num = ref(0)
const yesterdayCount = ref(0)
const getOptionsForAppAllPieRef = ref(getOptionsForAppAllPie([]))

// 活跃应用累计总量
const loadActiveAppAll = async () => {
  // 使用 await 同步获取请求结果
  const res = await getTotalActiveNum();
  const { data } = res.data;
  total_active_num_start.value = Number(total_active_num.value);
  total_active_num.value = Number(data.total_active_num);
  return; // 返回一个 Promise
}


//地图
const centerMapData = ref([])
//7天应用启动
const sevenNum = ref(0)
const sevenTotal = ref(0)
const getOptionsForRightpieSevenRef = ref(getOptionsForRightpie(sevenNum.value, sevenTotal.value, '活跃占比'))

//15天应用启动
const fifteenNum = ref(0)
const fifteenTotal = ref(0)
const getOptionsForRightpieRef = ref(getOptionsForRightpie(fifteenNum.value, fifteenTotal.value, '活跃占比'))

/**
 * 应用启动量查询
 * @param {String} type 
 */
const getAppStartTotalFn = (type) => {
  const yesterdayTime = getYesterday().replace(/-/g, '');
  const start7Time = getLast7Days()[0].replace(/-/g, '');
  const end7Time = getLast7Days().at(getLast7Days().length - 1).replace(/-/g, '');
  const start15Time = getLast15Days()[0].replace(/-/g, '');
  const end15Time = getLast15Days().at(getLast15Days().length - 1).replace(/-/g, '');
  const startLast30Time = getLast30Days()[0].replace(/-/g, '');
  const endLast30Time = getLast30Days().at(getLast30Days().length - 1).replace(/-/g, '');
  switch (type) {
    case 'yesterday':
      getStartTotal({ begintime: yesterdayTime, endtime: yesterdayTime }).then(res => {
        const { data } = res.data
        if (data.length > 0) {
          yesterdayCount.value = Number(data[0].daily_startup_num)
        }
      })
      break;
    case 'seven':
      getStartTotal({ begintime: start7Time, endtime: end7Time }).then(res => {
        const { data } = res.data
        if (data.length > 0) {
          const total = data.map(v => Number(v.daily_startup_num)).reduce((pre, cur) => pre + cur, 0)
          sevenTotal.value = total.toLocaleString()

          const sevenData = Number(data[data.length - 1].last_7_days_active_num)
          getOptionsForRightpieSevenRef.value = getOptionsForRightpie(sevenData, total_active_num.value, '活跃占比')
        }
      })
      break;
    case 'fifteen':
      getStartTotal({ begintime: start15Time, endtime: end15Time }).then(res => {
        const { data } = res.data
        if (data.length > 0) {
          const total = data.map(v => Number(v.daily_startup_num)).reduce((pre, cur) => pre + cur, 0)
          const fifteenData = Number(data[data.length - 1].last_15_days_active_num)
          fifteenTotal.value = total.toLocaleString()
          getOptionsForRightpieRef.value = getOptionsForRightpie(fifteenData, total_active_num.value, '活跃占比')
        }
      })
      break;
    case 'lineSeven':
      getStartTotal({ begintime: start7Time, endtime: end7Time, limit: '7' }).then(res => {
        const { data } = res.data
        data.forEach(v => {
          v.date = `${v.date.substring(0, 4)}-${v.date.substring(4, 6)}-${v.date.substring(6, 8)}`;
        })
        const xData = data.map(v => v.date)
        const yData = data.map(v => Number(v.daily_startup_num))
        getOptionsForLineBottomRef.value = getOptionsForLineBottom(xData, yData, currentTab.value)
      })
      break;
    case 'lineThirty':
      getStartTotal({ begintime: startLast30Time, endtime: endLast30Time, limit: '30' }).then(res => {
        const { data } = res.data
        data.forEach(v => {
          v.date = `${v.date.substring(0, 4)}-${v.date.substring(4, 6)}-${v.date.substring(6, 8)}`;
        })
        const xData = data.map(v => v.date)
        const yData = data.map(v => Number(v.daily_startup_num))
        getOptionsForLineBottomRef.value = getOptionsForLineBottom(xData, yData, currentTab.value)
      })
      break;
  }
}
//底部折线图
const xData = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']
const getOptionsForLineBottomRef = ref(getOptionsForLineBottom(xData, [], '1'))
const tabs = ref([
  { value: '1', label: '昨天' },
  { value: '2', label: '近7天' },
  { value: '3', label: '近30天' },
])
const currentTab = ref('1')
const getLineDataFn = () => {
  if (currentTab.value == 1) {
    getYesterdayStart().then(res => {
      const { data } = res;
      const yData = data.data.ydata.map(Number)
      getOptionsForLineBottomRef.value = getOptionsForLineBottom(data.data.xdata, yData, currentTab.value)
    })
  } else if (currentTab.value == 2) {
    getAppStartTotalFn('lineSeven')
  } else {
    getAppStartTotalFn('lineThirty')
  }
}

// const previousCount = ref(0);

/**
 * 加载地图数据
 */
const loadMapData = () => {
  getRegionSum().then(res => {
    const { data } = res.data
    if (data.length > 0 && data[0].data.length > 0) {
      const appSumData = data[0].data.map(item => {
        return {
          region_name: item.region_name,
          value: item.total_region_startup_num
        };
      });
      appSumData.sort((a, b) => {
        return b.value - a.value
      })
      getTodayRegionSum().then(res => {
        const { data } = res.data
        if (data) {
          const mergedData = appSumData.map(item => {
            const todayItem = data.find(v => v.region_name == item.region_name)
            if (todayItem) {
              return {
                ...item,
                name: todayItem.region_name,
                today: todayItem.today_region_startup_num
              }
            }
          }).filter(item => item !== undefined);
          const mapArr = china.features.map(item => {
            return { name: item.properties.name, value: '0', today: '0' }
          })
          mapArr.forEach(v => {
            if (!mergedData.find(item => item.name == v.name)) mergedData.push(v)
          })
          centerMapData.value = mergedData;
        } else {
          //无数据展示
          const mergedData = appSumData.map(item => {
            return {
              ...item,
              name: item.region_name,
              today: 0,
            }
          }).filter(item => item !== undefined);
          const mapArr = china.features.map(item => {
            return { name: item.properties.name, value: '0', today: '0' }
          })
          mapArr.forEach(v => {
            if (!mergedData.find(item => item.name == v.name)) mergedData.push(v)
          })
          centerMapData.value = mergedData;
        }
      })
    }
  })
}

// 今日应用总量
const loadtodayActiveApp = () => {
  getTodayAppStartUpNum().then(res => {
    const { data } = res.data
    if (data) {
      prevData.value = Number(data.today_app_startup_num);
      clearInterval(interval5minCount.value);
      if (window.sessionStorage.getItem('lastNumSdk')) {
        console.log(`sdk最新数据今日--prevData--${prevData.value}`);
        console.log(`sdk存量数据--today_app_startup_num--${today_app_startup_num.value}`);

        const lastNumStr = window.sessionStorage.getItem('lastNumSdk');
        const lastNumValue = lastNumStr ? Number(lastNumStr) : 0;
        // console.log('lastNumValue-->',lastNumValue)
        // console.log('lastNumStr-->',lastNumStr)
        let totalValue = Number(prevData.value) - lastNumValue;
        console.log(`初始数值/差值：${totalValue}`);

        if (totalValue <= 0) {
          today_app_startup_num.value = prevData.value;
          return;
        }

        const totalSeconds = 299; // 5分钟 * 60秒/分钟
        const consumeValuePerSecond = Math.floor(totalValue / totalSeconds);
        console.log(`每秒消耗的数值（取整）${consumeValuePerSecond}`);
        const lastSecondExtraConsume = totalValue - (consumeValuePerSecond * (totalSeconds - 1));

        let currentValue = totalValue;
        // eslint-disable-next-line
        function consumeValueSdk() {
          if (currentValue > 0) {
            if (currentValue <= lastSecondExtraConsume) {
              currentValue = 0;
              today_app_startup_num.value = prevData.value;
              today_app_startup_num_start.value = prevData.value;
            } else {
              currentValue -= consumeValuePerSecond;
              today_app_startup_num_start.value = today_app_startup_num.value;
              today_app_startup_num.value += consumeValuePerSecond;
            }
          } else {
            clearInterval(interval5minCount.value); // 清除定时器
          }
        }
        interval5minCount.value = setInterval(consumeValueSdk, 1000);
      } else {
        today_app_startup_num.value = Number(data.today_app_startup_num)
      }
    }
  })
}
onMounted(async () => {
  window.sessionStorage.removeItem('lastNumSdk')
  //活跃应用累计总量
  await loadActiveAppAll()
  //今日应用总量
  loadtodayActiveApp()
  //昨日启动总量
  getAppStartTotalFn('yesterday')
  //7天启动总量
  getAppStartTotalFn('seven')
  //15天启动总量
  getAppStartTotalFn('fifteen')
  //app 启动总量--截止当日为止
  getAppSum().then(res => {
    const { data } = res.data
    if (data.length > 0 && data[0].data.length > 0) {
      const appSumData = data[0].data.map(item => {
        return {
          name: item.app_name,
          value: Number(item.total_app_startup_num)
        };
      });
      getOptionsForAppAllPieRef.value = getOptionsForAppAllPie(appSumData)
    }
  })
  //地图数据
  loadMapData()
  // previousCount.value = today_app_startup_num.value
  //折线图
  getLineDataFn()
})
//tab选项卡
const currentTabClick = (value) => {
  currentTab.value = value
  getLineDataFn()
}
//5分钟刷新数据-累计应用总量/地图/今日应用总量
intervalId.value = setInterval(() => {
  window.sessionStorage.removeItem('lastNumSdk')
  window.sessionStorage.setItem('lastNumSdk', prevData.value)
  loadtodayActiveApp()
  loadActiveAppAll()
  loadMapData()
}, 5 * 1000 * 60)
intervalAllId.value = setInterval(() => {
  //昨日启动总量
  getAppStartTotalFn('yesterday')
  //7天启动总量
  getAppStartTotalFn('seven')
  //15天启动总量
  getAppStartTotalFn('fifteen')
}, (60 * 5) * 1000 * 60)
onUnmounted(() => {
  // 清除定时器
  if (intervalId.value) clearInterval(intervalId.value);
  if (intervalAllId.value) clearInterval(intervalAllId.value);
  if (interval5minCount.value) clearInterval(interval5minCount.value);
});
</script>
<style lang="scss" scoped>
.first-page {
  padding: 0 40px 60px 40px;

  .top-count {
    width: 100%;
    padding-top: 90px;
    display: flex;
    align-items: center;
    border-radius: 3px;
    margin-bottom: 25px;

    .item {
      height: 140px;
      display: flex;
      align-items: center;

      &.top-count-center {
        .num-box {
          display: flex;
          padding-top: 5px;
          font-size: 48px;

          .num-box-item {
            background: #ccc;
            margin-right: 10px;
            width: 40px;
            height: 60px;
            text-align: center;
            background: url('/src/assets/number_bg.png') no-repeat 0 0;
            background-size: 100% 100%;
            font-weight: bold;
          }
        }

        .text {
          opacity: 0.7;
          font-size: 24px;
          text-align: center;
        }

        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      &.top-count-right {
        .item-top {
          padding-left: 55px;
        }
      }

      &-top {
        &-r {
          padding-left: 20px;
        }

        display: flex;
        color:#fff;
        padding-left: 20px;

        .count {
          opacity: 0.7;
          font-size: 24px;
        }

        .text {
          font-size: 36px;
          font-weight: bold;
        }
      }
    }

    &-left {
      width: 28%;
      background: url('/src/assets/top_left_bg.png') no-repeat 0 0;
      background-size: 100% 100%;
    }

    &-center {
      width: 44%;
      background: url('/src/assets/top_center_bg.png') no-repeat 0 0;
      background-size: 100% 100%;
    }

    &-right {
      width: 28%;
      background: url('/src/assets/top_right_bg.png') no-repeat 0 0;
      background-size: 100% 100%;
    }
  }

  // center
  .center-box {
    width: 100%;
    height: 480px;
    display: flex;
    background-image: url('/src//assets/BG1.png');
    background-size: 100% 110%;
    background-repeat: no-repeat;

    &-left {
      width: 25%;
    }

    &-center {
      width: 50%;
      margin-left: 30px;
      margin-right: 30px;
    }

    &-right {
      width: 25%;

      .layout-right {
        padding-left: 20px;
        display: flex;
        align-items: center;
        height: 190px;

        &-num {
          font-size: 36px;
          color: #fff;
          font-weight: bold;
        }
      }

      &-top {
        height: 240px;
      }

      &-bottom {
        height: 200px;
      }
    }
  }

  //botter
  .bottom-box {
    height: 550px;

    &-left {
      height: 100%;
      width: 100%;
    }
  }
}

.no-bg {
  background: none !important;
  width: 20px !important;
}

.tab-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.tab-container {
  padding-top: 20px;
  padding-left: 40px;
}

.tabs {
  display: flex;
  border-radius: 10px;
}

.tabs-item {
  width: 100px;
  height: 36px;
  line-height: 36px;
  font-size: 16px;
  background: url('/src/assets/button_normal.png') 0 0 no-repeat;
  background-size: 100% 100%;
  color: #fff;
  cursor: pointer;
  text-align: center;
  margin-right: 10px;
  font-weight: bold;
}

.tabs-item.active {
  background: url('/src/assets/button_avtived.png') 0 0 no-repeat;
  background-size: 100% 100%;
  color: #4C98FF;
}

.flip-clock {
  display: flex;
}

.flip-card {
  perspective: 1000px;
  margin: 0 5px;
}

.flip-card-inner {
  transition: transform 0.3s;
  transform-style: preserve-3d;
}

.flip-card:hover .flip-card-inner {
  transform: rotateX(90deg);
}

.flip-card-front,
.flip-card-back {
  backface-visibility: hidden;
  position: absolute;
  width: 100%;
  height: 100%;
}

.flip-card-back {
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotateX(180deg);
}
</style>